package gota.util;

import gota.processingResources.*;
 
import java.io.*;
//import java.net.URL;
import java.util.*;

public final class GenericUtil {

	@SuppressWarnings("unchecked")
	public static Class[] GetClassesOfType(String packageName, Class classType)
			throws ClassNotFoundException, IOException, IllegalAccessException, InstantiationException {
		ArrayList<Class> retClasses = new ArrayList<Class>();
	
		Class[] classes = GetClasses(packageName);

		for (int i = 0; i < classes.length; i++) {
			if (classes[i].isInterface() == false
					&& classes[i].newInstance() instanceof IProcessingResource) {
				retClasses.add(classes[i]);
			}
		}

		return retClasses.toArray(new Class[retClasses.size()]);
	}

	@SuppressWarnings("unchecked")
	public static Class[] GetClasses(String packageName)
			throws ClassNotFoundException, IOException {
		//ClassLoader classLoader = Thread.currentThread()
		//		.getContextClassLoader();
		//assert classLoader != null;
		//String path = packageName.replace('.', '/');
		//Enumeration<URL> resources = classLoader.getResources(path);
		//List<File> dirs = new ArrayList<File>();
		//while (resources.hasMoreElements()) {
		//	URL resource = resources.nextElement();
		//	dirs.add(new File(resource.getFile()));
		//}
		ArrayList<Class> classes = new ArrayList<Class>();
                classes.add(DocumentResetResource.class);
                classes.add(GazetterResource.class);
                classes.add(NETransducerResource.class);
                classes.add(RegExSplitterResource.class);
                classes.add(UnicodeTokenizerResource.class);
                classes.add(OpenNLPPOSTagger.class);
		//for (File directory : dirs) {
		//	classes.addAll(findClasses(directory, packageName));
		//}
		return classes.toArray(new Class[classes.size()]);
	}

	@SuppressWarnings({ "unchecked", "unused" })
	private static List<Class> findClasses(File directory, String packageName)
			throws ClassNotFoundException {
		List<Class> classes = new ArrayList<Class>();
		if (!directory.exists()) {
			return classes;
		}
		File[] files = directory.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				assert !file.getName().contains(".");
				classes.addAll(findClasses(file, packageName + "."
						+ file.getName()));
			} else if (file.getName().endsWith(".class")) {
				classes.add(Class.forName(packageName
						+ '.'
						+ file.getName().substring(0,
								file.getName().length() - 6)));
			}
		}
		return classes;
	}
}
